var host_name = window.location.host;
if(host_name == 'dev.admin.bossjob.com'){
    // develop
    var API_HOSTNAMES = {
            'admin'    : 'https://dev.api.admin.bossjob.com',
            'document' : 'http://dev.document.bossjob.com',
            'data_api' : 'http://dev.data.bossjob.com',
            'pc'       : 'http://dev.bossjob.ph',
    };
} else if(host_name == 'staging.admin.bossjob.com'){
    // staging
    var API_HOSTNAMES = {
            'admin'    : 'http://staging.admin.bossjob.com:8079',
            'document' : 'http://staging.document.bossjob.com',
            'data_api' : 'http://staging.data.bossjob.com',
            'pc'       : 'http://staging.yolo.funny.bossjob.ph'
    };
} else if(host_name == 'admin.bossjob.com'){
    // product
    var API_HOSTNAMES = {
            'admin'    : 'http://admin.bossjob.com:8079',
            'document' : 'http://document.bossjob.com',
            'data_api' : 'http://data.bossjob.com',
            'pc'       : 'http://www.bossjob.ph'
    };
} else {
    // local
    var API_HOSTNAMES = {
	'admin'    : 'http://news.local.com',
	'document' : 'http://dev.document.bossjob.com',
	'data_api' : 'http://dev.data.bossjob.com',
	'pc'       : 'http://dev.bossjob.ph',
    };
}
(function(){
	function Storage(){
		Storage.prototype.cache =  function(key, value, expire){
			var expireTo = parseInt(new Date().getTime()) + expire;
			var _cachedExpire = this.get('_cache', {});
			_cachedExpire[key] = expireTo;
			this.set('_cache', _cachedExpire);
			this.set(key, value);
		}
		Storage.prototype.set = function(key, value){
			localStorage[key] = JSON.stringify(value);
		}
		Storage.prototype.get = function(key, _default=false){
			var _value = localStorage[key] == undefined ? '{}' : localStorage[key];
			_value = JSON.parse(_value);
			return JSON.stringify(_value) != "{}" ? _value : _default;
		}
		Storage.prototype.getExpireTo = function(key){
			var _cachedExpire = this.get('_cache', {});
			return _cachedExpire[key] == undefined ? 0 : parseInt(_cachedExpire[key]);
		}
	}
	function Token(){
		this.storage = new Storage('localStorage');
		Token.prototype.getToken = function(){
			// var now = parseInt(new Date().getTime());
			// var expireTime = this.storage.getExpireTo('token');
			// console.log('now='+now+',expire='+expireTime);
			// if(now > expireTime){
			// 	var _this = this;
			// 	setTimeout(function(){
			// 		_this.refreshToken();
			// 	}, 3000);
			// }
			return this.storage.get('token', false);
		}
		Token.prototype.setToken = function(token){
			return this.storage.cache('token', token, 5000);
		}
		Token.prototype.refreshToken = function(){
			window.Api.Patch('refreshToken', {}, function(object, error){
				if(object['data']){
					var token = object['data']['token'];
					(new Token()).setToken(token);
				}
			});
		}
	}
	function Api(){
		this.storage = new Storage('localStorage');
		this.apis = {};
		// Api.prototype.init = function(){
		// 	if(window.XMLHttpRequest){
		// 		xhr = new XMLHttpRequest();
		// 	}else{
		// 		xhr = new ActiveXObject('Microsoft.XMLHttp');
		// 	}
		// 	xhr.open('GET', '/_resource/html/navigation.html');
		// 	xhr.send();
		// 	xhr.onreadystatechange = function(){
		// 		if(xhr.readyState == 4){
		// 			document.getElementById('bossjob-admin-body').innerHTML = xhr.responseText;
		// 		}
		// 	}
		// }
		Api.prototype.set = function(key, value){
			this.storage.set(key, value);
		}
		Api.prototype.get = function(key, _default=false){
			return this.storage.get(key, _default);
		}
		// this.token = (new Token()).getToken();
		Api.prototype.setApis = function(apis){
			this.apis = apis;
		}
		Api.prototype.Patch = function(apiname, data, callback){
			if(apiname == 'refreshToken'){
				var options = {'Authorization':'Bearer '+this.storage.get('token', false)};
			}else{
				var options = {'Authorization':'Bearer '+(new Token()).getToken()};
			}
			this.request('PATCH', this.apis[apiname], data, callback, options);
		}
		Api.prototype.Post = function(apiname, data, callback, postType='x-www-form-urlencoded', dataFilter={}){
			if(apiname != 'login' && apiname != 'uploadImages'){
				var options = {'Authorization':'Bearer '+(new Token()).getToken()};
			}else{
				var options = {};
			}
			if(this.isApiNameNeedToRender(apiname)){
				var url = this.render(this.apis[apiname], data);
			}else{
				var url = this.apis[apiname];
			}
			if(postType == 'x-www-form-urlencoded'){
				options['Content-Type'] = 'application/x-www-form-urlencoded';
				var dataArr = [];
				for(k in data){
					if(dataFilter[k]){
						continue;
					}
					dataArr.push(k+'='+data[k]);
				}
				data = dataArr.join('&');
			}
			if(apiname == 'login'){
				_callback = callback;
				callback = function(object, error){
					if(object['data']){
						var token = object['data']['token'];
						(new Token()).setToken(token);
					}
					_callback(object, error);
				}
			}
			this.request('POST', url, data, callback, options);
		}
		Api.prototype.Get = function(apiname, data, callback, dataFilter={}){
			var options = {'Authorization':'Bearer '+(new Token()).getToken()};
			if(this.isApiNameNeedToRender(apiname)){
				var url = this.render(this.apis[apiname], data);
			}else{
				var url = this.apis[apiname];
			}
			if(typeof data == 'object'){
				var dataArr = [];
				for(k in data){
					if(dataFilter[k]){
						continue;
					}
					dataArr.push(k+'='+data[k]);
				}
				data = dataArr.join('&');
				this.request('GET', url+(data.length == 0 ? '' : '?')+data, {}, callback, options);
			}else{
				this.request('GET', url+'/'+data, {}, callback, options);
			}
		}
		Api.prototype.Delete = function(apiname, data, callback){
			var options = {'Authorization':'Bearer '+(new Token()).getToken()};
			if(this.isApiNameNeedToRender(apiname)){
				var url = this.render(this.apis[apiname], data);
			}else{
				var url = this.apis[apiname];
			}
			var dataArray = [];
			for(k in data){
				dataArray.push(k+'='+data[k]);
			}
			this.request('DELETE', url+'?'+dataArray.join('&'), {}, callback, options);
		}
		Api.prototype.Put = function(apiname, data, callback, dataFilter={}){
			var options = {'Authorization':'Bearer '+(new Token()).getToken()};
			if(this.isApiNameNeedToRender(apiname)){
				var url = this.render(this.apis[apiname], data);
			}else{
				var url = this.apis[apiname];
			}
			var dataArray = [];
			for(k in data){
				if(dataFilter[k]){
					continue;
				}
				dataArray.push(k+'='+data[k]);
			}
			this.request('PUT', url+'?'+dataArray.join('&'), {}, callback, options);
		}
		Api.prototype.isApiNameNeedToRender = function(apiname){
			return (-1 != this.apis[apiname].indexOf('{') && -1 != this.apis[apiname].indexOf('}')) ? true : false;
		}
		Api.prototype.render = function(template, data){
			for(k in data){
				var value = data[k],
					reg = new RegExp('{'+k+'}', "g");
				template = template.replace(reg, value);
			}
			return template;
		}
		Api.prototype.U = function(file, param, domain=''){
			if(domain == ''){
				var paramArray = [];
				for(k in param){
					paramArray.push(k+'='+param[k]);
				}
				return file+'?'+paramArray.join('&');
			}else{
				return domain+this.render(file, param);				
			}
		}
		Api.prototype.Params = function(){
			var paramStr = window.location.href.split('?');
			if(paramStr[1]){
				paramArray = paramStr[1].split('&');
				var rtn = {};
				for(var i=0; i<paramArray.length; ++i){
					var temp = paramArray[i].split('=');
					rtn[temp[0]] = temp[1];
				}
				return rtn;
			}else{
				return {};
			}
		}
		Api.prototype.request = function(method, url, data=null, callback, options=[]){
			if(window.XMLHttpRequest){
				xhr = new XMLHttpRequest();
			}else{
				xhr = new ActiveXObject('Microsoft.XMLHttp');
			}
			xhr.open(method, url);
			if(options.length != 0){
				for(header in options){
					xhr.setRequestHeader(header, options[header]);
				}
			}
			try{
				xhr.send(data);
			}catch(e){

			}
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					try{
						var object = JSON.parse(xhr.responseText);
						var error = false;
					}catch(e){
						var error = {
							_self : e,
							name : e.name,
							number : e.number,
							message : e.message,
							fileName : e.fileName,
							stack : e.stack,
						};
						var object = {};
					}
					if(xhr.status == 200){
						callback(object, error);
					}else{
						if(xhr.status == 401){
							if(callback(object, error)){
								setTimeout(function(){
									window.Api.set('token', false);
									window.Api.set('user', false);
									window.Api.set('access', false);
									window.location.reload();
								}, 3000);
							}
						}else{
							callback(object, error);
						}
					}
				}
			}
		}
		Api.prototype.isSuccess = function(object, error){
			if(!error && object['message'] && object['status_code'] && object['message'] == 'OK' && object['status_code'] == 200){
				return true;
            }else{
            	return false;
            }
		}
		Api.prototype.getAdminPagenation = function(totalRows, totalPages, currentPage, callback){
			var ulStart = '<ul class="pagination">',
				totalTemplate = '<li><span>{totalRows} records, {totalPages} pages</span></li>',
				rowTemplate = '<li class="{activeClass}" data-page="{page}"><a href="#">{page}</a></li>',
				ulEnd = '</ul>',
				pages = [];

			var pageDomString = '';
			pageDomString = pageDomString + ulStart;
			pageDomString = pageDomString + window.Api.render(totalTemplate, {totalRows:totalRows, totalPages:totalPages});

			var currentLeft = Math.min(2, currentPage-1);
			if(1 < currentPage-2){
				pages.push(1);
				pages.push('...');
			}
			for(var i=Math.max(1, currentPage-2); i<currentPage; ++i){
				pages.push(i);
			}
			var currentRight = Math.min(currentPage+2, totalPages);
			for(var i=currentPage; i<=currentRight; ++i){
				pages.push(i);
			}
			if(totalPages > currentPage+2){
				pages.push('...');
				pages.push(totalPages);
			}
			for(var i=0; i<pages.length; ++i){
				pageDomString = pageDomString + window.Api.render(rowTemplate, {activeClass:pages[i]==currentPage?'active':'', callback:callback, page:pages[i]});
			}
			pageDomString = pageDomString + ulEnd;
			return pageDomString;
		}
	}

	window.Api = new Api();
	window.Api.setApis({
		'login' : API_HOSTNAMES['admin']+'/api/v1/auth/login',
		'refreshToken' : API_HOSTNAMES['admin']+'/api/v1/auth/refresh',
		'logout' : API_HOSTNAMES['admin']+'/api/v1/auth/invalidate',
		'getUser' : API_HOSTNAMES['admin']+'/api/v1/auth/user',
		'changeDefaultPassword' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/modifyPass',
		'createFaqCate' : API_HOSTNAMES['admin']+'/api/v1/faqCate/add',
		'saveFaqCate' : API_HOSTNAMES['admin']+'/api/v1/faqCate/edit',
		'getFaqCateList' : API_HOSTNAMES['admin']+'/api/v1/faqCate/listCategory',
		'deleteFaqCate' : API_HOSTNAMES['admin']+'/api/v1/faqCate/delete',
		'openFaqCate' : API_HOSTNAMES['admin']+'/api/v1/faqCate/open',
		'closeFaqCate' : API_HOSTNAMES['admin']+'/api/v1/faqCate/close',
		'getFaqCateDetail' : API_HOSTNAMES['admin']+'/api/v1/faqCate/detail',
		'createFaq' : API_HOSTNAMES['admin']+'/api/v1/faq/add',
        'closeFaq' : API_HOSTNAMES['admin']+'/api/v1/faq/close',
        'deleteFaq' : API_HOSTNAMES['admin']+'/api/v1/faq/delete',
        'getFaqDetail' : API_HOSTNAMES['admin']+'/api/v1/faq/detail',
        'saveFaq' : API_HOSTNAMES['admin']+'/api/v1/faq/edit',
        'getFaqList' : API_HOSTNAMES['admin']+'/api/v1/faq/listFaq',
        'openFaq' : API_HOSTNAMES['admin']+'/api/v1/faq/open',
        'getNewsCategoryList' : API_HOSTNAMES['admin']+'/api/v1/category/listCategory',
        'deleteNewsCategory' : API_HOSTNAMES['admin']+'/api/v1/category/delete',
        'openNewsCategory' : API_HOSTNAMES['admin']+'/api/v1/category/open',
        'closeNewsCategory' : API_HOSTNAMES['admin']+'/api/v1/category/close',
        'createNewsCate' : API_HOSTNAMES['admin']+'/api/v1/category/add',
		'getNewsCateDetail' : API_HOSTNAMES['admin']+'/api/v1/category/detail',
		'saveNewsCate' : API_HOSTNAMES['admin']+'/api/v1/category/edit',
		'getNewsList' : API_HOSTNAMES['admin']+'/api/v1/news/listNews',
        'deleteNews' : API_HOSTNAMES['admin']+'/api/v1/news/delete',
        'openNews' : API_HOSTNAMES['admin']+'/api/v1/news/publish',
        'closeNews' : API_HOSTNAMES['admin']+'/api/v1/news/draft',
        'createNews' : API_HOSTNAMES['admin']+'/api/v1/news/add',
		'getNewsDetail' : API_HOSTNAMES['admin']+'/api/v1/news/detail',
		'saveNews' : API_HOSTNAMES['admin']+'/api/v1/news/edit',
		'getNodeList' : API_HOSTNAMES['admin']+'/api/v1/rbacNode/list',
 		'saveNode' : API_HOSTNAMES['admin']+'/api/v1/rbacNode/edit', 
 		'createNode' : API_HOSTNAMES['admin']+'/api/v1/rbacNode/add', 
 		'deleteNode' : API_HOSTNAMES['admin']+'/api/v1/rbacNode/delete', 
 		'getRbacUserList' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/list',
 		'deleteRbacUser' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/delete',
 		'getRbacUserDetail' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/detail',
 		'openRbacUser' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/open',
 		'closeRbacUser' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/close',
 		'createRBACUser' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/add',
 		'initRBACUserPassword' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/initPassword',
 		'saveProfile' : API_HOSTNAMES['admin']+'/api/v1/rbacUser/saveProfile',
 		'getRbacRoleList' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/list',
 		'openRbacRole' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/open',
 		'closeRbacRole' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/close',
 		'deleteRbacRole' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/delete',
 		'createRbacRole' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/add',
 		'getRoleAccess' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/access',
 		'setRoleAccess' : API_HOSTNAMES['admin']+'/api/v1/rbacRole/setAccess',
 		'getUserList' : API_HOSTNAMES['admin']+'/api/v1/data/listUser',
 		'changeUserStatus' : API_HOSTNAMES['data_api']+'/api/v1/admins/users/{id}/change_status',
 		'getUserInfo' : API_HOSTNAMES['data_api']+'/api/v1/users/{id}',
 		'getRecruiterInfo' : API_HOSTNAMES['data_api']+'/api/v1/admins/recruiters/{ruid}',
 		'updateUserTopInfo' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}',
 		'deleteUserEducationExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/educations/{eduId}',
 		'addEduExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/educations',
 		'updateEduExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/educations/{eduId}',
 		'deleteUserWorkExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/work_xps/{workId}',
 		'updateUserWorkExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/work_xps/{workId}',
 		'createUserWorkExperience' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/work_xps',
 		'deleteUserJobPreference' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/preferences/{preferenceId}',
 		'createUserJobPerference' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/preferences',
 		'updateUserJobPerference' : API_HOSTNAMES['data_api']+'/api/v1/users/{uid}/preferences/{preferenceId}',
 		'getCompanyListForAutoComplete' : API_HOSTNAMES['data_api']+'/api/v1/company_lists',
 		'getJobTitleListForAutoComplete' : API_HOSTNAMES['data_api']+'/api/v1/job_lists',
                'getAuthToolList' : API_HOSTNAMES['data_api']+'/api/v1/admins/documents?status_key={status_key}&document_type={document_type}&per_page={per_page}&page={page}',
                'updateVerifyRecruiter' : API_HOSTNAMES['data_api']+'/api/v1/admins/documents/verify_recruiter',
                'updateVerifyCompnay'   : API_HOSTNAMES['data_api']+'/api/v1/admins/documents/verify_company',
                'updateRejectRecruiter' : API_HOSTNAMES['data_api']+'/api/v1/admins/documents/reject_recruiter',
                'updateRejectCompnay'   : API_HOSTNAMES['data_api']+'/api/v1/admins/documents/reject_company',
 		'getSchoolList' : API_HOSTNAMES['data_api']+'/api/v1/school_lists',
 		'getCompanyList' : API_HOSTNAMES['admin']+'/api/v1/data/listCompany',
                'getCompanyDetail' : API_HOSTNAMES['data_api']+'/api/v1/companies/{companyId}',
                'updateCompnay' : API_HOSTNAMES['data_api']+'/api/v1/companies/{coordinator_id}',
                'getConfigInfo' : API_HOSTNAMES['data_api']+'/api/v1/config?country_code={country_code}',
                'uploadImages'  : API_HOSTNAMES['document']+'/public/uploadImages'
	});
})();
